#pragma once
#include <iostream>
#include <functional>
#include <signal.h>

#include "Socket.hpp"
#include "Log.hpp"

using func_t = std::function<std::string(std::string& package)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback)
        :_port(port), _callback(callback)
    {}

    void Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        log(Info, "server init ... done");
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = _listensock.Accept(&clientip, &clientport);
            if(sockfd < 0) continue;
            log(Info, "accept a new link, sockfd: %d, client ip: %s, port: %d", sockfd, clientip.c_str(), clientport);

            if(fork() == 0)
            {
                _listensock.Close();
                std::string inbuffer_stream;

                // 数据计算
                while (true)
                {
                    char buffer[128];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if(n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;

                        log(Debug, "debug:\n %s", inbuffer_stream.c_str());

                        while (true)    // 可能客户端一次发送多次请求
                        {
                            std::string info = _callback(inbuffer_stream);
                            if(info.empty()) break;

                            write(sockfd, info.c_str(), info.size());
                        }      
                    }
                    else break;
                }
                exit(0);
            }
        }
        
    }

    ~TcpServer() {}
private:
    uint16_t _port;
    Sock _listensock;
    func_t _callback;
};